import { isNotNull } from '../utils';

export default {
  name: 'co-tabs',
  provide () {
    return {
      tabClick: this.handleTabClick,
      getDefaultVal: this.getDefaultVal,
      addTab: this.addTab,
      removeTab: this.removeTab,
      getActiveValue: this.getActiveValue
    };
  },
  props: {
    fullWidth: Boolean,
    center: Boolean,
    value: {}
  },
  data () {
    return {
      tabs: [],
      activeValue: isNotNull(this.value) ? this.value : 0
    };
  },
  created () {
    this.tabIndex = 0;
  },
  methods: {
    handleTabClick (value) {
      if (this.activeValue !== value) {
        this.activeValue = value;
        this.$emit('update:value', value);
        this.$emit('change', value);
      }
    },
    getActiveValue () {
      return this.activeValue;
    },
    getDefaultVal () {
      return this.tabIndex++;
    },
    addTab (tab) {
      const index = this.$children.indexOf(tab);
      return index === -1 ? this.tabs.push(tab) : this.tabs.splice(index, 0, tab);
    },
    removeTab (tab) {
      const index = this.tabs.indexOf(tab);
      if (index === -1) return;
      this.tabs.splice(index, 1);
    },
    getActiveTab () {
      return this.tabs.filter((tab) => tab.active)[0];
    }
  },
  watch: {
    value (val) {
      this.activeValue = val;
    }
  },
  render (h) {
    return h('div', {
      staticClass: 'co-tabs',
      class: {
        'co-tabs--full-width': this.fullWidth,
        'co-tabs--center': this.center
      }
    }, [
      this.$slots.default
    ]);
  }
};
